package com.llt.music.controller;

import com.llt.music.model.User;
import com.llt.music.service.UserService;
import com.llt.music.tools.Result;
import com.llt.music.tools.Constant;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("login")
    public Result login(String username, String password, HttpServletRequest request) {
        log.info("正在登陆....................");

        User user = userService.selectByName(username);

        if (user == null) {
            log.error("用户名或密s码错误");
            return Result.fail("用户名或密码错误");
        }else {
            // 比较当前密码和数据库存的是否一样
            boolean flg = bCryptPasswordEncoder.matches(password, user.getPassword());
            if (!flg) {
                log.error("用户名或密码错误");
                return Result.fail("用户名或密码错误");
            }
        }

        log.info("登陆成功");

        request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY, user);

        return Result.success("登陆成功", user);
    }
}
